import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import {
  Card,
  Button,
  Form,
  Row,
  Col,
  Input,
  Spin,
  BackTop,
  Select,
  DatePicker,
  notification,
  Icon,
  Popover,
  Affix,
  Upload,
  Modal,
  // message,
} from 'antd';
// import axios from 'axios';

import { refitFieldDecoratorOption, refitCommonData, getTokenKeyName } from '../../../utils/tools';
// import FooterToolbar from '../../../components/FooterToolbar';
import styles from './BasicInfo.less';
// import { request } from '@/utils/request';

const { TextArea } = Input;
const FormItem = Form.Item;
// const { MonthPicker } = DatePicker;

const fieldLabels = {
  title: '商品名称',
  subtitle: '副标题',
  origin: '产地',
  number: '编号',
  specification: '规格',
  unit: '单位',
  buyType: '销售渠道',
  saleType: '销售类型',
  rank: '所属类别',
  shareTitle: '分享标题',
  shareDescription: '分享描述',
  image: '图片',
  stock: '库存',
  costPrice: '进货价格',
  salePrice: '销售价格',
  expressPrice: '配送价格',
  marketPrice: '市场价格',
  stockPrice: '服务站价格',
  pushMoney: '提成',
  score: '积分',
  access: '访问量',
  publishTime: '发布时间',
};

@connect(({ product, global, loading }) => ({
  product,
  global,
  loading: loading.models.product,
}))
@Form.create()
class BasicInfo extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      // width: '100%',
      metaData: {},
      dataLoading: true,
      saving: false,
      tokenSet: null,
      previewVisible: false,
      previewImage: '',
      fileList: [
        {
          uid: '-1',
          name: 'xxx.png',
          status: 'done',
          url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
        },
      ],
    };
  }

  componentDidMount() {
    this.isMountedFlag = true;

    const { match } = this.props;
    const { params } = match;
    const { id: productId } = params;

    const tokenSetObject = {};
    tokenSetObject[`${getTokenKeyName()}`] = localStorage.getItem(getTokenKeyName()) || '';
    this.setState({ tokenSet: tokenSetObject });

    this.loadData(productId);
  }

  loadData = id => {
    const { dispatch } = this.props;

    let productId = id;
    productId = 21;

    this.setState({ dataLoading: true }, () => {
      dispatch({
        type: 'product/get',
        payload: {
          pid: productId,
        },
      }).then(() => {
        if (this.isMountedFlag) {
          const {
            product: {
              data: { data },
            },
          } = this.props;
          this.setState({ dataLoading: false, metaData: data });
        }
      });
    });
  };

  refitFieldDecoratorOption = (v, justice, defaultValue, originalOption) => {
    const result = originalOption;

    if (justice) {
      result.initialValue = v || (defaultValue || '');
    }

    return result;
  };

  handleSubmit = e => {
    e.preventDefault();
    const {
      dispatch,
      form,
      location: { pathname },
    } = this.props;
    const { metaData } = this.state;
    form.validateFields((err, values) => {
      if (!err) {
        this.setState({ saving: true });
        const submitValue = values;
        submitValue.image = metaData.image;

        dispatch({
          type: 'product/updateBasicInfo',
          payload: submitValue,
        }).then(() => {
          this.setState({ saving: false });
          const {
            product: { data },
          } = this.props;
          const { code, message: messageText } = data;
          if (code === 200) {
            notification.success({
              placement: 'bottomRight',
              message: '操作结果',
              description: '数据已经保存成功，请进行后续操作。',
            });
          } else {
            notification.error({
              placement: 'bottomRight',
              message: '操作结果',
              description: messageText,
            });
          }

          dispatch(
            routerRedux.replace({
              pathname: `${pathname.replace('/load/', '/update/')}`,
            })
          );
        });
      }
    });
  };

  buildFieldDescription = (v, op, other) => {
    const o = (other || '') === '' ? '' : `,${other}`;
    return `请${op || '输入'}${v}${o}!`;
  };

  buyTypeList = () => {
    const { global } = this.props;
    return refitCommonData(global.buyTypeList);
  };

  rankList = () => {
    const { global } = this.props;
    return refitCommonData(global.rankList);
  };

  saleTypeList = () => {
    const { global } = this.props;
    return refitCommonData(global.saleTypeList);
  };

  unitList = () => {
    const { global } = this.props;
    return refitCommonData(global.unitList);
  };

  handleFormReset = () => {
    const { dispatch, form } = this.props;
    form.resetFields();
    dispatch({
      type: 'product/getCurrent',
      payload: {},
    }).then(() => {
      const {
        product: { data },
      } = this.props;
      this.setState({ metaData: data });
      this.setState({ saving: false });
    });
  };

  getErrorInfo = () => {
    const {
      form: { getFieldsError },
    } = this.props;
    const errors = getFieldsError();
    const errorCount = Object.keys(errors).filter(key => errors[key]).length;
    if (!errors || errorCount === 0) {
      return null;
    }
    const scrollToField = fieldKey => {
      const labelNode = document.querySelector(`label[for="${fieldKey}"]`);
      if (labelNode) {
        labelNode.scrollIntoView(true);
      }
    };
    const errorList = Object.keys(errors).map(key => {
      if (!errors[key]) {
        return null;
      }
      return (
        <li key={key} className={styles.errorListItem} onClick={() => scrollToField(key)}>
          <Icon type="cross-circle-o" className={styles.errorIcon} />
          <div className={styles.errorMessage}>{errors[key][0]}</div>
          <div className={styles.errorField}>{fieldLabels[key]}</div>
        </li>
      );
    });
    return (
      <span className={styles.errorIcon}>
        <Popover
          title="表单校验信息"
          content={errorList}
          overlayClassName={styles.errorPopover}
          trigger="click"
          getPopupContainer={trigger => trigger.parentNode}
        >
          <Icon type="exclamation-circle" />
        </Popover>
        {errorCount}
      </span>
    );
  };

  // resizeFooterToolbar = () => {
  //   requestAnimationFrame(() => {
  //     const sider = document.querySelectorAll('.ant-layout-sider')[0];
  //     if (sider) {
  //       const width = `calc(100% - ${sider.style.width})`;
  //       const { width: stateWidth } = this.state;
  //       if (stateWidth !== width) {
  //         this.setState({ width });
  //       }
  //     }
  //   });
  // };

  validate = () => {
    const {
      form: { validateFieldsAndScroll },
      dispatch,
      location: { pathname },
    } = this.props;
    const { metaData } = this.state;

    validateFieldsAndScroll((error, values) => {
      if (!error) {
        this.setState({ saving: true });
        const submitValue = values;
        submitValue.image = metaData.image;

        dispatch({
          type: 'product/updateBasic',
          payload: submitValue,
        }).then(() => {
          const {
            product: { data },
          } = this.props;
          const { code } = data;
          if (code === 200) {
            notification.success({
              placement: 'bottomRight',
              message: '操作结果',
              description: '数据已经保存成功，请进行后续操作。',
            });
          }

          this.setState({ saving: false }, () => {
            dispatch(
              routerRedux.replace({
                pathname: `${pathname.replace('/load/', '/update/')}`,
              })
            );
          });
        });
      }
    });
  };

  handleUploadCancel = () => this.setState({ previewVisible: false });

  handlePreview = file => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };

  handleUploadChange = ({ fileList }) => {
    this.setState({ fileList: [...fileList] });
  };

  render() {
    const { form } = this.props;
    const {
      metaData,
      saving,
      //  width,
      dataLoading,
      tokenSet,
      previewVisible,
      previewImage,
      fileList,
    } = this.state;
    const { getFieldDecorator } = form;

    const buyTypeData = this.buyTypeList();
    const buyTypeOption = [];

    buyTypeData.forEach(item => {
      const { name, flag } = item;
      buyTypeOption.push(
        <Select.Option key={flag} value={flag}>
          {name}
        </Select.Option>
      );
    });

    const rankData = this.rankList();
    const rankOption = [];

    rankData.forEach(item => {
      const { name, flag } = item;
      rankOption.push(
        <Select.Option key={flag} value={flag}>
          {name}
        </Select.Option>
      );
    });

    const saleTypeData = this.saleTypeList();
    const saleTypeOption = [];

    saleTypeData.forEach(item => {
      const { name, flag } = item;
      saleTypeOption.push(
        <Select.Option key={flag} value={flag}>
          {name}
        </Select.Option>
      );
    });

    const unitData = this.unitList();
    const unitOption = [];

    unitData.forEach(item => {
      const { name, flag } = item;
      unitOption.push(
        <Select.Option key={flag} value={flag}>
          {name}
        </Select.Option>
      );
    });

    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传新图</div>
      </div>
    );

    const uploadProps = {
      action: 'http://api2.liangzivip.com/Product/GetProductMainImgUpload',
      listType: 'picture-card',
      fileList,
      onPreview: this.handlePreview,
      onChange: this.handleUploadChange,
      headers: { ...tokenSet },
    };

    return (
      <Fragment>
        <div className={styles.containorBox}>
          <Card
            title="品名与描述"
            className={styles.card}
            bordered={false}
            extra={
              <Affix offsetTop={20}>
                {this.getErrorInfo()}
                <Button
                  type="primary"
                  icon="save"
                  disabled={dataLoading}
                  // onClick={this.handleSaveBasicInfo}
                  onClick={this.validate}
                  loading={saving}
                >
                  保存
                </Button>
              </Affix>
            }
          >
            <Spin spinning={dataLoading || saving}>
              <Form layout="vertical">
                <Row gutter={24}>
                  <Col lg={12} md={12} sm={24}>
                    <FormItem label={fieldLabels.title}>
                      {getFieldDecorator(
                        'title',
                        refitFieldDecoratorOption(metaData.chvtitle, metaData.chvtitle, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.title),
                            },
                          ],
                        })
                      )(<Input placeholder={this.buildFieldDescription(fieldLabels.title)} />)}
                    </FormItem>
                  </Col>
                  <Col lg={12} md={12} sm={24}>
                    <FormItem label={fieldLabels.subtitle}>
                      {getFieldDecorator(
                        'subtitle',
                        refitFieldDecoratorOption(metaData.chvsubtitle, metaData.chvsubtitle, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.subtitle),
                            },
                          ],
                        })
                      )(<Input placeholder={this.buildFieldDescription(fieldLabels.subtitle)} />)}
                    </FormItem>
                  </Col>
                </Row>
                <Row gutter={16}>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.origin}>
                      {getFieldDecorator(
                        'origin',
                        refitFieldDecoratorOption(metaData.origin, metaData.origin, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.origin),
                            },
                          ],
                        })
                      )(<Input placeholder={this.buildFieldDescription(fieldLabels.origin)} />)}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.number}>
                      {getFieldDecorator(
                        'number',
                        refitFieldDecoratorOption(metaData.number, metaData.number, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.number),
                            },
                          ],
                        })
                      )(<Input placeholder={this.buildFieldDescription(fieldLabels.number)} />)}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.specification}>
                      {getFieldDecorator(
                        'specification',
                        refitFieldDecoratorOption(
                          metaData.specification,
                          metaData.specification,
                          '',
                          {
                            rules: [
                              {
                                required: false,
                                message: this.buildFieldDescription(fieldLabels.specification),
                              },
                            ],
                          }
                        )
                      )(
                        <Input
                          placeholder={this.buildFieldDescription(fieldLabels.specification)}
                        />
                      )}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.unit}>
                      {getFieldDecorator(
                        'unit',
                        refitFieldDecoratorOption(metaData.unit, metaData.unit, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.unit, '选择'),
                            },
                          ],
                        })
                      )(
                        <Select
                          placeholder={this.buildFieldDescription(fieldLabels.unit, '选择')}
                          // onChange={handleChange}
                        >
                          {unitOption}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                </Row>
                <Row gutter={24}>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.buyType}>
                      {getFieldDecorator(
                        'buyType',
                        refitFieldDecoratorOption(metaData.buyType, metaData.buyType, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.buyType, '选择'),
                            },
                          ],
                        })
                      )(
                        <Select
                          placeholder={this.buildFieldDescription(fieldLabels.buyType, '选择')}
                          // onChange={handleChange}
                        >
                          {buyTypeOption}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.rank}>
                      {getFieldDecorator(
                        'rank',
                        refitFieldDecoratorOption(metaData.rank, metaData.rank, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.rank),
                            },
                          ],
                        })
                      )(
                        <Select
                          placeholder={this.buildFieldDescription(fieldLabels.rank, '选择')}
                          // onChange={handleChange}
                        >
                          {rankOption}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.saleType}>
                      {getFieldDecorator(
                        'saleType',
                        refitFieldDecoratorOption(metaData.saleType, metaData.saleType, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.saleType, '选择'),
                            },
                          ],
                        })
                      )(
                        <Select
                          placeholder={this.buildFieldDescription(fieldLabels.saleType, '选择')}
                          // onChange={handleChange}
                        >
                          {saleTypeOption}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24} />
                </Row>
              </Form>
            </Spin>
          </Card>
          <Card title="库存、价格、提成与积分" className={styles.card} bordered={false}>
            <Spin spinning={dataLoading || saving}>
              <Form layout="vertical">
                <Row gutter={16}>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.stock}>
                      {getFieldDecorator(
                        'stock',
                        refitFieldDecoratorOption(metaData.stock, metaData.stock, 0, {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.stock),
                            },
                          ],
                        })
                      )(<Input placeholder={this.buildFieldDescription(fieldLabels.stock)} />)}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.costPrice}>
                      {getFieldDecorator(
                        'costPrice',
                        refitFieldDecoratorOption(metaData.costPrice, metaData.costPrice, 0, {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.costPrice),
                            },
                          ],
                        })
                      )(
                        <Input
                          addonBefore="￥"
                          placeholder={this.buildFieldDescription(fieldLabels.costPrice)}
                        />
                      )}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.stockPrice}>
                      {getFieldDecorator(
                        'stockPrice',
                        refitFieldDecoratorOption(metaData.stockPrice, metaData.stockPrice, 0, {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.stockPrice),
                            },
                          ],
                        })
                      )(
                        <Input
                          addonBefore="￥"
                          placeholder={this.buildFieldDescription(fieldLabels.stockPrice)}
                        />
                      )}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.salePrice}>
                      {getFieldDecorator(
                        'salePrice',
                        refitFieldDecoratorOption(metaData.salePrice, metaData.salePrice, 0, {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.salePrice),
                            },
                          ],
                        })
                      )(
                        <Input
                          addonBefore="￥"
                          placeholder={this.buildFieldDescription(fieldLabels.salePrice)}
                        />
                      )}
                    </FormItem>
                  </Col>
                </Row>
                <Row gutter={16}>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.marketPrice}>
                      {getFieldDecorator(
                        'marketPrice',
                        refitFieldDecoratorOption(metaData.marketPrice, metaData.marketPrice, 0, {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.marketPrice),
                            },
                          ],
                        })
                      )(
                        <Input
                          addonBefore="￥"
                          placeholder={this.buildFieldDescription(fieldLabels.marketPrice)}
                        />
                      )}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.expressPrice}>
                      {getFieldDecorator(
                        'expressPrice',
                        refitFieldDecoratorOption(metaData.expressPrice, metaData.expressPrice, 0, {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.expressPrice),
                            },
                          ],
                        })
                      )(
                        <Input
                          addonBefore="￥"
                          placeholder={this.buildFieldDescription(fieldLabels.expressPrice)}
                        />
                      )}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.pushMoney}>
                      {getFieldDecorator(
                        'pushMoney',
                        refitFieldDecoratorOption(metaData.pushMoney, metaData.pushMoney, 0, {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.pushMoney),
                            },
                          ],
                        })
                      )(
                        <Input
                          addonBefore="￥"
                          placeholder={this.buildFieldDescription(fieldLabels.pushMoney)}
                        />
                      )}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.score}>
                      {getFieldDecorator(
                        'score',
                        refitFieldDecoratorOption(metaData.score, metaData.score, 0, {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.score),
                            },
                          ],
                        })
                      )(<Input placeholder={this.buildFieldDescription(fieldLabels.score)} />)}
                    </FormItem>
                  </Col>
                </Row>
              </Form>
            </Spin>
          </Card>
          <Card title="图片信息" className={styles.card} bordered={false}>
            <Spin spinning={dataLoading || saving}>
              <Form layout="vertical" />
              <div className="clearfix">
                <Upload {...uploadProps}>{fileList.length >= 3 ? null : uploadButton}</Upload>
                <Modal visible={previewVisible} footer={null} onCancel={this.handleUploadCancel}>
                  <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
              </div>
            </Spin>
          </Card>

          <Card title="分享设置" className={styles.card} bordered={false}>
            <Spin spinning={dataLoading || saving}>
              <Form className="ant-advanced-search-form">
                <Row gutter={24}>
                  <Col span={12}>
                    <FormItem label="分享标题">
                      {getFieldDecorator(
                        'shareTitle',
                        refitFieldDecoratorOption(metaData.shareTitle, metaData.shareTitle, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.shareTitle),
                            },
                          ],
                        })
                      )(
                        <TextArea
                          placeholder="请输入分享标题"
                          autosize={{ minRows: 3, maxRows: 5 }}
                        />
                      )}
                    </FormItem>
                  </Col>
                  <Col span={12}>
                    <FormItem label="分享描述">
                      {getFieldDecorator(
                        'shareDescription',
                        refitFieldDecoratorOption(
                          metaData.shareDescription,
                          metaData.shareDescription,
                          '',
                          {
                            rules: [
                              {
                                required: false,
                                message: this.buildFieldDescription(fieldLabels.shareDescription),
                              },
                            ],
                          }
                        )
                      )(
                        <TextArea
                          placeholder="请输入分享描述"
                          autosize={{ minRows: 3, maxRows: 5 }}
                        />
                      )}
                    </FormItem>
                  </Col>
                </Row>
              </Form>
            </Spin>
          </Card>
          <Card title="其他设置" className={styles.card} bordered={false}>
            <Spin spinning={dataLoading || saving}>
              <Form layout="vertical">
                <Row gutter={16}>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.access}>
                      {getFieldDecorator(
                        'access',
                        refitFieldDecoratorOption(metaData.access, metaData.access, 0, {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.access),
                            },
                          ],
                        })
                      )(<Input placeholder={this.buildFieldDescription(fieldLabels.access)} />)}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24}>
                    <FormItem label={fieldLabels.publishTime}>
                      {getFieldDecorator(
                        'publishTime',
                        refitFieldDecoratorOption(metaData.publishTime, metaData.publishTime, '', {
                          rules: [
                            {
                              required: false,
                              message: this.buildFieldDescription(fieldLabels.publishTime),
                            },
                          ],
                        })
                      )(
                        <DatePicker
                          style={{ width: '100%' }}
                          showTime
                          format="YYYY-MM-DD HH:mm:ss"
                          placeholder={this.buildFieldDescription(fieldLabels.publishTime)}
                        />
                      )}
                    </FormItem>
                  </Col>
                  <Col lg={6} md={12} sm={24} />
                  <Col lg={6} md={12} sm={24} />
                </Row>
              </Form>
            </Spin>
          </Card>
        </div>
        <BackTop />
      </Fragment>
    );
  }
}

export default BasicInfo;
